<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Generating Deferreds</title>
</head>

<!-- status of document: INCOMPLETE, DRAFT -->

<body>

<h1>Generating Deferreds</h1>

<p><code class="API" base="twisted.internet.defer">Deferred</code> objects are
signals that a function you have called does not yet have the data you want
available. When a function returns a Deferred object, your calling function
attaches callbacks to it to handle the data when available.</p>

<p>This document addresses the other half of the question: writing functions
that return Deferreds, that is, constructing Deferred objects, arranging for
them to be returned immediately without blocking until data is available, and
firing their callbacks when the data is available.</p>

<p>This document assumes that you are familiar with the <a
href="async.xhtml">asynchronous model</a> used by Twisted, and with <a
href="defer.xhtml">using deferreds returned by functions</a>.</p>

<a name="class"></a>

<h2>Class overview</h2>

<p>This is an overview API reference for Deferred from the point of creating a
Deferred and firing its callbacks and errbacks.  It is not meant to be a
substitute for the docstrings in the Deferred class, but can provide
guidelines for its use.</p>

<p>There is a parallel overview of functions used by calling function which
the Deferred is returned to at <a href="defer.xhtml#class">Using Deferreds</a>.</p>

<h3>Basic Callback Functions</h3>

<ul>
  <li>
  <code class="py-prototype">callback(result)</code> 
  
  <p>Run success callbacks with the given result. <em>This
  can only be run once.</em> Later calls to this or
  <code>errback</code> will raise <code
  class="API">twisted.internet.defer.AlreadyCalledError</code>.
  If further callbacks or errbacks are added after this
  point, addCallbacks will run the callbacks immediately.</p>
  </li>
  
  <li>
  <code class="py-prototype">errback(failure)</code> 
  
  <p>Run error callbacks with the given failure. <em>This can
  only be run once.</em> Later calls to this or
  <code>callback</code> will raise <code
  class="API">twisted.internet.defer.AlreadyCalledError</code>.
  If further callbacks or errbacks are added after this
  point, addCallbacks will run the callbacks immediately.</p>
  </li>
</ul>

<h2>What Deferreds don't do: make your code asynchronous</h2>

<p><em>Deferreds do not make the code magically not block.</em></p>

<p>Let's take this function as an example:</p>

<pre class="python">
from twisted.internet import defer
    
TARGET = 10000

def largeFibonnaciNumber():
    # create a Deferred object to return:
    d = defer.Deferred()

    # calculate the ten thousandth Fibonnaci number

    first = 0
    second = 1

    for i in xrange(TARGET - 1):
        new = first + second
        first = second
        second = new
        if i % 100 == 0:
            print "Progress: calculating the %dth Fibonnaci number" % i

    # give the Deferred the answer to pass to the callbacks:
    d.callback(second)

    # return the Deferred with the answer:
    return d

import time

timeBefore = time.time()

# call the function and get our Deferred
d = largeFibonnaciNumber()

timeAfter = time.time()

print "Total time taken for largeFibonnaciNumber call: %0.3f seconds" % \
      (timeAfter - timeBefore)

# add a callback to it to print the number

def printNumber(number):
    print "The %dth Fibonacci number is %d" % (TARGET, number)

print "Adding the callback now."

d.addCallback(printNumber)
</pre>

<p>You will notice that despite creating a Deferred in the
<code>largeFibonnaciNumber</code> function, these things happened:</p>
<ul>
<li>the &quot;Total time taken for largeFibonnaciNumber call&quot; output
shows that the function did not return immediately as asynchronous functions
are expected to do; and</li>
<li>rather than the callback being added before the result was available and
called after the result is available, it isn't even added until after the
calculation has been completed.</li>
</ul>

<p> The function completed its calculation before returning, blocking the
process until it had finished, which is exactly what asynchronous functions
are not meant to do.  Deferreds are not a non-blocking talisman: they are a
signal for asynchronous functions to <em>use</em> to pass results onto
callbacks, but using them does not guarantee that you have an asynchronous
function.</p>


<h2>Advanced Processing Chain Control</h2>

<ul>
  <li>
  <code class="py-prototype">pause()</code> 
  
  <p>Cease calling any methods as they are added, and do not
  respond to <code>callback</code>, until
  <code>self.unpause()</code> is called.</p>
  </li>
  
  <li>
  <code class="py-prototype">unpause()</code> 
  
  <p>If <code>callback</code> has been called on this
  Deferred already, call all the callbacks that have been
  added to this Deferred since <code>pause</code> was
  called.</p>
  
  <p>Whether it was called or not, this will put this
  Deferred in a state where further calls to
  <code>addCallbacks</code> or <code>callback</code> will
  work as normal.</p>
  </li>
</ul>

<h2>Returning Deferreds from synchronous functions</h2>

<p>Sometimes you might wish to return a Deferred from a synchronous function.
There are several reasons why, the major two are maintaining API compatibility
with another version of your function which returns a Deferred, or allowing
for the possiblity that in the future your function might need to be
asynchronous.</p>

<p>In the <a href="defer.xhtml">Using Deferreds</a> reference, we gave the
following example of a synchronous function:</p>

<a href="listings/deferred/synch-validation.py"
class="py-listing">synch-validation.py</a>

<p>While we can require that callers of our function wrap our synchronous
result in a Deferred using <code class="API"
base="twisted.internet.defer">maybeDeferred</code>, for the sake of API
compatibility it is better to return a Deferred ourself using  <code
class="API" base="twisted.internet">defer.succeed</code>:</p>

<pre class="python">
from twisted.internet import defer

def immediateIsValidUser(user):
    '''
    Returns a Deferred resulting in true if user is a valid user, false
    otherwise
    '''
    
    result = user in ["Alice", "Angus", "Agnes"]
    
    # return a Deferred object already called back with the value of result
    return defer.succeed(result)
</pre>

<p>There is an equivalent <code class="API"
base="twisted.internet">defer.fail</code> method to return a Deferred with the
errback chain already fired.</p>

<h2>Integrating blocking code with Twisted</h2>

<p>At some point, you are likely to need to call a blocking function: many
functions in third party libraries will have long running blocking functions.
There is no way to 'force' a function to be asynchronous: it must be written
that way specifically. When using Twisted, your own code should be
asynchronous, but there is no way to make third party functions asynchronous
other than rewriting them.</p>

<p>In this case, Twisted provides the ability to run the blocking code in a
separate thread rather than letting it block your application. The <code
class="API">twisted.internet.threads.deferToThread</code> function will set up
a thread to run your blocking function, return a Deferred and later fire that
Deferred when the thread completes.</p>

<p>Let's assume our <code class="python">largeFibonnaciNumber</code> function
from above is in a third party library (returning the result of the
calculation, not a Deferred) and is not easily modifiable to be finished in
discrete blocks. This example shows it being called in a thread, unlike in the
earlier section we'll see that the operation does not block our entire
program:</p>

<pre class="python">
def largeFibonnaciNumber():
    """
    Represent a long running blocking function by calculating
    the TARGETth Fibonnaci number
    """
    TARGET = 10000

    first = 0
    second = 1

    for i in xrange(TARGET - 1):
        new = first + second
        first = second
        second = new

    return second

from twisted.internet import threads, reactor

def fibonacciCallback(result):
    """
    Callback which manages the largeFibonnaciNumber result by
    printing it out
    """
    print "largeFibonnaciNumber result =", result
    # make sure the reactor stops after the callback chain finishes,
    # just so that this example terminates
    reactor.stop()

def run():
    """
    Run a series of operations, deferring the largeFibonnaciNumber
    operation to a thread and performing some other operations after
    adding the callback
    """
    # get our Deferred which will be called with the largeFibonnaciNumber result
    d = threads.deferToThread(largeFibonnaciNumber)
    # add our callback to print it out
    d.addCallback(fibonacciCallback)
    # unless the largeFibonnaciNumber thread returns very fast, these print
    #lines should happen first
    print "1st line after the addition of the callback"
    print "2nd line after the addition of the callback"

if __name__ == '__main__':
    run()
    reactor.run()
</pre>

<h2>Possible sources of error</h2>

<p>Deferreds greatly simplify the process of writing asynchronous code by
providing a standard for registering callbacks, but there are some subtle and
sometimes confusing rules that you need to follow if you are going to use
them. This mostly applies to people who are writing new systems that use
Deferreds internally, and not writers of applications that just add callbacks
to Deferreds produced and processed by other systems. Nevertheless, it is good
to know.</p>

<h3>Firing Deferreds more than once is impossible</h3>

<p>Deferreds are one-shot. You can only call <code>Deferred.callback</code> or
<code>Deferred.errback</code> once. The processing chain continues each time
you add new callbacks to an already-called-back-to Deferred.</p>

<h3>Synchronous callback execution</h3>

<p>If a Deferred already has a result available, addCallback
<strong>may</strong> call the callback synchronously: that is, immediately
after it's been added.  In situations where callbacks modify state, it is
might be desirable for the chain of processing to halt until all callbacks are
added. For this, it is possible to <code>pause</code> and <code>unpause</code>
a Deferred's processing chain while you are adding lots of callbacks.</p>

<p>Be careful when you use these methods! If you <code>pause</code> a
Deferred, it is <em>your</em> responsibility to make sure that you unpause it.
The function adding the callbacks must unpause a paused Deferred, it should
<em>never</em> be the responsibility of the code that actually fires the
callback chain by calling <code>callback</code> or <code>errback</code> as
this would negate its usefulness!</p>

</body>
</html>
